import axios from 'axios'

const api = axios.create({
  baseURL: '/api',
  timeout: 10000,
})

export interface RateResponse {
  ts_utc: string
  base: string
  quote: string
  rate: number
  amount_1000: number
}

export interface LatestRatesResponse {
  jpy_cny: RateResponse
  jpy_usd: RateResponse
  last_updated: string
}

export interface HealthResponse {
  status: string
  timestamp: string
  database_connected: boolean
}

export const apiService = {
  // 健康检查
  async getHealth(): Promise<HealthResponse> {
    const response = await api.get('/health')
    return response.data
  },

  // 获取最新汇率
  async getLatestRates(): Promise<LatestRatesResponse> {
    const response = await api.get('/last')
    return response.data
  },

  // 获取汇率时间序列
  async getRates(
    quote: 'CNY' | 'USD',
    start?: string,
    end?: string,
    interval: '30m' | '1d' = '1d'
  ): Promise<RateResponse[]> {
    const params = new URLSearchParams({
      quote,
      interval,
    })
    
    if (start) params.append('start', start)
    if (end) params.append('end', end)
    
    const response = await api.get(`/rates?${params}`)
    return response.data
  },

  // 手动触发策略评估
  async triggerEvaluation(): Promise<{ message: string }> {
    const response = await api.post('/trigger-eval')
    return response.data
  },

  // 手动触发数据拉取
  async triggerFetch(): Promise<{ message: string }> {
    const response = await api.post('/trigger-fetch')
    return response.data
  },
}
